﻿using BooksLib.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BooksLib.Repositories
{
    class MyBooksSampleRepository
    {
        private List<MyBook> _books;
        public MyBooksSampleRepository()
        {
            //初始化仓储（当前数据源来自列表）
            InitSampleBooks();
        }

        /// <summary>
        /// 初始化数据仓库，当前数据源来自列表
        /// </summary>
        private void InitSampleBooks()
        {
            _books = new List<MyBook>()
            {
                new MyBook { ID=1, BookName = "C#从入门到精通", Author = "清华大学出版社" },
                new MyBook { ID = 2, BookName = "软件工程", Author = "电子工业出版社" },
                new MyBook { ID = 3, BookName= "模式设计", Author = "机械工业出版社" }
            };
        }

        /// <summary>
        /// 异步删除指定id的书
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回bool值</returns>
        public Task<bool> DeleteAsync(int id)
        {

            MyBook bookToDelete = _books.Find(b => b.ID == id);
            if (bookToDelete != null)
            {
                //_books.Remove(bookToDelete)，其中_books是List集合，其中Remove方法是同步方法
                //当前方法要求返回值是在异步任务下返回bool
                //因此，使用Task.FromResult将同步方法调用结果，以成功的异步任务形式返回
                return Task.FromResult<bool>(_books.Remove(bookToDelete));
            }

            return Task.FromResult<bool>(false);
        }

        /// <summary>
        /// 异步获取指定id的书
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回书</returns>
        public Task<MyBook> GetItemAsync(int id)
        {
            //使用Task.FromResult将同步方法调用结果，以成功的异步任务形式返回
            return Task.FromResult(_books.Find(b => b.ID == id));
        }

        /// <summary>
        /// 异步获取所有书
        /// </summary>
        /// <returns></returns>
        public Task<IEnumerable<MyBook>> GetItemsAsync()
        {
            return Task.FromResult<IEnumerable<MyBook>>(_books);
        }


        /// <summary>
        /// 异步更新某本书
        /// </summary>
        /// <param name="item"></param>
        /// <returns>返回更新后的书</returns>
        public Task<MyBook> UpdateAsync(MyBook item)
        {
            MyBook bookToUpdate = _books.Find(b => b.ID == item.ID);
            if (bookToUpdate == null) return null;
            int ix = _books.IndexOf(bookToUpdate);
            _books[ix] = item;
            return Task.FromResult(_books[ix]);
        }
        /// <summary>
        /// 异步添加书到存储库
        /// </summary>
        /// <param name="item"></param>
        /// <returns>返回添加后的书</returns>

        public Task<MyBook> AddAsync(MyBook item)
        {

            item.ID = _books.Select(b => b.ID).Max() + 1;
            _books.Add(item);
            return Task.FromResult(item);
        }
    }
}
